<!DOCTYPE html>
<html lang="en">
<head>
<title>角色管理</title>
	<div th:include="base-libs-easyui :: base-libs-easyui" />

<style type="text/css">
body {
	padding: 0px 10px;
}

.datagrid-header-row, .datagrid-row {
	height: 32px;
}

.datagrid-row-selected{
	background-color: #3071A9;
}
</style>

<script th:inline="javascript">
	/**读取request中的初始化数据*/
	var data = [[${data}]];
</script>
<script type="text/javascript">
	$(function() {
		initView();
        $(this).registerManagerPage({
            cacheTables: ["TB_ZY_JGLB"]
            ,callback: initData
        });
	});
	
	function initView() {
		$("#btnSave").on("click", btnSaveHandler);
		$("#btnBack").on("click", btnBackHandler);

		$("body").on("change", ".actionCheckbox", function(evt){
		    var checked = $(this).prop("checked");
            var menuid = $(this).attr("menuid");
            if(StringUtils.isEmpty(menuid)){
            	menuid = $(this).attr("NAVIGATE");
            }
            var node = $('#treeMenu').treegrid("find", menuid);
            if(node)
			{
			    var ACTIONSARY = node["ACTIONSARY"];
			    if(ACTIONSARY)
				{
                    var id = $(this).attr("id");
				    $.each(ACTIONSARY, function(index, item){
						if(item["CONTROL_ID"] == id)
						{
						    item["state"] = checked;
						    return false;
						}
					})
				}
			}
			/*如果选择功能 则默认选择菜单*/
		    if(checked)
			{
                $('#treeMenu').treegrid("checkNode", menuid);
			}
		});

        $("#combTreeWsjglb").combotree({
            height: 30
            ,width: 212
            ,panelWidth: 212
            ,editable: true
			,checkbox : true
			,multiple : true
        });

		/* easyui树  */
        $('#treeMenu').treegrid({
            idField : 'MENUID',
            treeField : 'MENUNAME',
            animate : true,
            checkbox: true,
            fitColumns : true,
            border : false,
            scrollbarSize : 2,
            columns : [ [
                {
                    title : '菜单编码',
                    field : 'MENUID',
                    width : 20
                }
                ,{
                    title : '菜单名称',
                    field : 'MENUNAME',
                    width : 50
                },{
                    title : '是否导航',
                    field : 'NAVIGATE',
                    width : 20
                    ,formatter: function(value,row,index){
                        var MENUID = row["MENUID"];
                        var radio = "";
                        if(row["children"]){
                            radio = "<div hidden='hidden'><label style='padding-right: 8px; margin-bottom: 0px; display: inline-block;'>"
                                + "<input name='" + MENUID + "'  NAVIGATE='" + MENUID + "' value='1' type='radio' checked='true' style='vertical-align: middle; margin-top: auto; width: 14px; background-color: transparent; border: none;'>";
                        }else{
                            radio =  "<div><label style='padding-right: 8px; margin-bottom: 0px; display: inline-block;'>"
                                + "<input name='" + MENUID + "'  NAVIGATE='" + MENUID + "' value='1' type='radio' class='actionCheckbox' style='vertical-align: middle; margin-top: auto; width: 14px; background-color: transparent; border: none;'>";
                        }

                        radio += "<span style='vertical-align: middle;'>是</span></label><label style='padding-right: 8px; margin-bottom: 0px; display: inline-block;'>"
                            + "<input name='" + MENUID + "'  NAVIGATE='" + MENUID + "' value='0' type='radio' class='actionCheckbox' style='vertical-align: middle; margin-top: auto; width: 14px; background-color: transparent; border: none;'>"
                            + "<span style='vertical-align: middle;'>否</span></label></div>" ;
                        return radio ;
                    }
                },{
                    title : '路径',
                    field : 'VIEWURL',
                    width : 50
                },{
                    title : '菜单功能',
                    field : 'ACTIONSARY',
                    width : 100
                    ,formatter: function(value,row,index){
                        var actionCheckBoxs = [];
                        var MENUID = row["MENUID"];
						if(value)
						{
							$.each(value, function(){
								var text = this["ACTION_NAME"];
								var checkbox = "<label style='padding-right: 8px; margin-bottom: 0px; display: inline-block;'>"
									+"<input id='" + this["CONTROL_ID"] + "' class='actionCheckbox' menuid='" + MENUID + "' type='checkbox' style='vertical-align: middle; margin-top: auto; width: 14px; background-color: transparent; border: none;'>" +
									"<span style='vertical-align: middle;'>" + text + "</span></label>";
								actionCheckBoxs.push($(checkbox).prop("outerHTML"));
							})
						}
                        return actionCheckBoxs.join("");
                    }
                }
			]]
			,onDblClickRow: function(row){
                $('#treeMenu').treegrid("toggle", row["MENUID"]);
			}
        });
	}
	
	function btnSaveHandler(evt)
	{
		var id = $(evt.currentTarget).attr("id");
		if($(".form-control").QuickValidate() && validate())
		{

			var params = getSelectedMenuAndActions();
            var ROLETYPE = $("#combTreeWsjglb").combotree("getValues");
            var TYPE_DESCRIBE = $("#combTreeWsjglb").combotree("getText");
			if(!StringUtils.isEmpty(ROLETYPE)){
                params["ROLETYPE"] = ROLETYPE;
                params["TYPE_DESCRIBE"] = TYPE_DESCRIBE;
			}
			$.QuickRemote.AjaxFiledFormSubmit("formRole", saveHandler, params, {btnId: id});
		}
	}

	/*获取设置卫生机构类别*/
    function getROLETYPE(){
        var role = $("#formRole").data("role");
        var value = "2";
        if(StringUtils.isEmpty(role) || StringUtils.isEmpty(role["SUPER"])){
            value = $("#combTreeWsjglb").combotree("getValues");
            value = value.join(",");
		}
        return value;
    }

    function setROLETYPE(yljgxx){
		/*设置卫生机构类别*/
        $("#combTreeWsjglb").val(yljgxx["WSJGLBDM"]);
        $.QuickEasyUIUtils.setComboTreeValue("combTreeWsjglb", yljgxx["WSJGLBDM"]);
    }
	
	function saveHandler(result, addParams)
	{
		var state = result["state"];
		if(state)
		{
			$.QuickAlert.alertNormal("保存成功", {callback: function(){
				if("btnSaveAndConfig" == addParams["btnId"])
				{
					$.QuickAlert.alertConfirm({content: "是否继续配置人员", callback: function(){
						location = "";
					}})
				}
				else
				{
					$("#btnBack").trigger("click");
				}
			}});
		}
		else
		{
			var info = result["info"];
			$.QuickAlert.alertFail({content: info["faultInfo"]});
		}
	}
	
	/**验证菜单是否勾选*/
	function validate()
	{
		var valid = true;
		var ary = $("#treeMenu").treegrid("getCheckedNodes");
		if(ary == null || ary.length<=0)
		{
			$.QuickAlert.alertFail({content: "请勾选菜单"});
			valid = false;
		}
		return valid;
	}
	
	/**获取所有勾选的菜单和功能*/
	function getSelectedMenuAndActions()
	{
		var menuIds = [];
		var menuActions = [];
		var menuNavigates = [];
		/*treegrid getCheckedNodes 不能获取中间状态的checkbox 所以采用直接获取dom*/
		$(".tree-checkbox1, .tree-checkbox2").each(function(){
		    var tr = $(this).parents("tr");
		    var nodeId = $(tr).attr("node-id");
            menuIds.push(nodeId);
            var idsAry = [];
            $("input:checkbox[menuid='" + nodeId + "']:checked").each(function(){
                idsAry.push($(this).attr("id"));
			});
            var NAVIGATE = $("input:radio[NAVIGATE='" + nodeId + "']:checked");
            if(NAVIGATE.length > 0 ){
            	menuNavigates.push(NAVIGATE.eq(0).val());
            }else{
            	menuNavigates.push("0");
            }
            if(idsAry.length>0)
            {
                var ids = idsAry.join(",");
                var menuAction = {MENUID: nodeId, CONTROL_IDS: ids};
                menuActions.push(menuAction);
            }
		})
		return {menuIds: menuIds, menuActions: JSON.stringify(menuActions),menuNavigates : menuNavigates.join(",")};
	}

	/**返回回调*/
	function btnBackHandler()
	{
		$.QuickUrlUtils.redirectUrl("index.html");
	}

	function initData(cacheData) {

		/*卫生机构类别*/
        var ary = cacheData["TB_ZY_JGLB"];
        var jglbTree = $.QuickEasyUIUtils.createTreeList(ary.concat(), ary[0]["SJDM"], "XMDM", "XMMC", "SJDM");
        $("#combTreeWsjglb").combotree("loadData", jglbTree);

        var menuList = data["menuList"];
        var dsTree = createTreeList(menuList.concat(),
            menuList[0]["PRE_MENUID"]);
        $('#treeMenu').treegrid('loadData', dsTree).treegrid('expandAll');

		var roleScope = data["roleScope"];
		$("#ROLETYPE").createOptions(roleScope, {needNull: "true"});
		
		var role = StoreCache.removeCache("cache_role");
		if(role)
		{
			$("#formRole").data("role", role);
//			if(!StringUtils.isEmpty(role["SUPER"])){
//				$("#combTreeWsjglb").removeClass("form-control");
//			}
			$(".form-control").each(function(){
                var name = $(this).attr("name");
				/*特殊控件另外赋值*/
                if(!StringUtils.isEmpty(name) && name != "WSJGLBDM" ){
                    var value = role[name];
                    $(this).QuickField("setData", value);
                }
			})
			if(!StringUtils.isEmpty(role["SUPER"])){
				$(".jsqxfw").hide();
			}else{
                var types = role['ROLETYPE'].split(",");
                $("#combTreeWsjglb").combotree("setValues", types);
            }
            //setWSJGLBDM(role["ROLETYPE"]);
			/*全部菜单*/
			var menuList = data["menuList"];
			/*因为存储是直接存成树形结构 所以这里不能勾选节点 而是反选节点*/
			/*勾选根节点*/
            var node = $("#treeMenu").treegrid("getRoot");
            $("#treeMenu").treegrid("checkNode", node["MENUID"]);
            /*反选节点*/
            $.each(menuList, function(index, item){
                var MENUID = item["MENUID"];
                if(!isExistRoleMenu(MENUID)){
                    $("#treeMenu").treegrid("uncheckNode", MENUID);
				}
			})
			/*勾选菜单功能*/
			var roleMenuAction = data["roleMenuAction"];
			$.each(roleMenuAction, function(index, item){
			    var MENUID = item["MENUID"];
			    var CONTROL_IDS = item["CONTROL_IDS"];
				checkAction(MENUID, CONTROL_IDS);
			})
		}
	}

	/**勾选菜单功能*/
	function checkAction(MENUID, CONTROL_IDS)
	{
	    var idAry = CONTROL_IDS.split(",");
	    $.each(idAry, function(){
            $("input:checkbox[menuid='" + MENUID + "'][id='" + this + "']").prop("checked", true);
		})
	}

	/**在角色菜单中是否存在*/
	function isExistRoleMenu(menuId)
	{
		var isExist = false;
		/*角色对应的菜单*/
        var roleMenu = data["roleMenu"];
        $.each(roleMenu, function(index, item){
            var roleMenuId = item["MENUID"];
            if(menuId == roleMenuId){
                isExist = true;
                var NAVIGATE = item["NAVIGATE"];
                $("input:radio[NAVIGATE='" + roleMenuId + "']").each(function(){
                	if(this.value == NAVIGATE){
                		$(this).prop("checked", true);
                	}
                });
                return false;
			}
		})
		return isExist;
	}
	
	/**封装树形结构*/
	function createTreeList(list, sjjgdm) {
		var childList = [];
		for (var i = 0; i < list.length; i++) {
			var item = list[i];
			if (item == null) {
				continue;
			}
			var sjjgdm1 = item["PRE_MENUID"];
			var ACTIONS = item["ACTIONS"];
			if(!StringUtils.isEmpty(ACTIONS))
			{
                ACTIONS = JSON.parse(ACTIONS);
                item["ACTIONSARY"] = ACTIONS;
                delete item["ACTIONS"];
			}
			if (sjjgdm1 != sjjgdm) {
				continue;
			} else {
				var resid = item["MENUID"];
				item["text"] = item["MENUNAME"];
				item["id"] = item["MENUID"];
				var lt = createTreeList(list, resid);
				if (lt != null && lt.length != 0) {
					item["children"] = lt;
				}
				childList.push(item);
				list[i] = null;
			}
		}
		if (childList.length == 0) {
			childList = null;
		}
		return childList;
	}
</script>
</head>
<body class="easyui-layout">
	<div region="north" style="height: 41px; border: none; overflow: hidden; background-color: #f9f9f9;">
		<div class="title">
			<h3>角色信息</h3>
		</div>
	</div>
	<div region="center" style="border: none;">
		<div class="easyui-layout" fit="true">
			<div region="north" style="height: 120px; overflow: hidden;" data-options="collapsible:false">
				<div style="padding: 6px 0px;">
					<button id="btnBack" style=" margin-left: 10px;" type="button">返回</button>
					<button id="btnSave" style=" margin-left: 10px;" type="button">保存</button>
				</div>
				<div class="easyui-panel" style="height: 80px;" title="角色基本信息">
					<form id="formRole" action="save">
						<table class="form-table">
							<tr>
								<td class="td-text">
									<label>角色名称</label>
								</td>
								<td class="td-content">
									<input class="form-control" type="text" name="ROLENAME"
										   placeholder="角色名称" quick-config="label:'角色名称', validateProxy:'notNull length', length: '64'" />
									<input name="ROLEID" class="form-control" style="display: none;"/>
								</td>
								<div id="jsqxfw">
								<td class="td-text jsqxfw" >
									<label>角色权限范围</label>
								</td>
								<td class="td-content jsqxfw" >
									<input id="combTreeWsjglb" name="WSJGLB" class="form-control"
										   quick-config="label:'角色权限范围', validateProxy:'notNull',  getDataFunction: 'getROLETYPE', setDataFunction: 'setROLETYPE'">
								</td>
								</div>
							</tr>
						</table>
					</form>
				</div>
			</div>
			<div region="center" title="角色菜单息">
				<table id="treeMenu" fit="true"></table>
			</div>
		</div>
		<!--<div class="easyui-panel" title="角色菜单息">-->

		<!--</div>-->
	</div>
</div>
</body>
</html>
